package com.ruoyi.fitsculpt.controller.app;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.fitsculpt.controller.EasyfitUsersController;
import com.ruoyi.fitsculpt.domain.EasyfitUsers;
import com.ruoyi.fitsculpt.domain.dto.AppLoginDTO;
import com.ruoyi.fitsculpt.service.IEasyfitUsersService;
import com.ruoyi.fitsculpt.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/app/easyfit/users")
@Api(tags = "小程序用户接口")
@Slf4j
public class AppEasyfitUsersController extends EasyfitUsersController {

    @Autowired
    private IEasyfitUsersService userService;

    /**
     * 查询用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(EasyfitUsers easyfitUsers) {
        return super.list(easyfitUsers);
    }

    /**
     * 获取用户详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return super.getInfo(id);
    }

    /**
     * 新增用户
     */
    @PostMapping
    public AjaxResult add(@RequestBody EasyfitUsers easyfitUsers) {
        return super.add(easyfitUsers);
    }

    /**
     * 修改用户
     */
    @PutMapping
    public AjaxResult edit(@RequestBody EasyfitUsers easyfitUsers) {
        return super.edit(easyfitUsers);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return super.remove(ids);
    }


    @ApiOperation("小程序用户登录")
    @PostMapping("/login")
    public AjaxResult login(@RequestBody AppLoginDTO loginDTO) {
        try {
            // 验证手机号是否为空
            if (loginDTO.getPhone() == null || loginDTO.getPhone().isEmpty()) {
                return error("手机号不能为空");
            }

            EasyfitUsers existUser = userService.selectEasyfitUsersByPhone(loginDTO.getPhone());

            if (existUser == null) {
                // 新用户注册
                EasyfitUsers user = new EasyfitUsers();
                user.setPhone(loginDTO.getPhone());
                user.setNickName(loginDTO.getNickName());
                user.setAvatar(loginDTO.getAvatar());
                user.setOpenid(loginDTO.getOpenid());
                user.setCreateTime(new Date());
                user.setStatus("0");
                userService.insertEasyfitUsers(user);
                existUser = user;
            } else {
                // 更新用户信息
                if (loginDTO.getNickName() != null) {
                    existUser.setNickName(loginDTO.getNickName());
                }
                if (loginDTO.getAvatar() != null) {
                    existUser.setAvatar(loginDTO.getAvatar());
                }
                if (loginDTO.getOpenid() != null) {
                    existUser.setOpenid(loginDTO.getOpenid());
                }
            }

            existUser.setLastLoginTime(new Date());
            existUser.setLastLoginIp(IpUtils.getIpAddr());
            userService.updateEasyfitUsers(existUser);

            String token = TokenUtils.generateToken(existUser);

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", existUser);

            return success(result);
        } catch (Exception e) {
            log.error("用户登录异常", e);
            return error("登录失败");
        }
    }


    /*
     *//**
     * 微信登录
     *//*
    @PostMapping("/wxLogin")
    @ApiOperation("微信登录")
    @ApiImplicitParam(name = "user", value = "用户信息", required = true)
    public AjaxResult wxLogin(@RequestBody EasyfitUsers user) {
        // 验证用户
        EasyfitUsers loginUser = userService.selectEasyfitUsersByOpenid(user.getOpenid());
        if (loginUser == null) {
            return AjaxResult.error("用户不存在");
        }

        // 生成token - 直接调用静态方法
        String token = TokenUtils.generateToken(loginUser);

        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", loginUser);

        return AjaxResult.success("登录成功", result);
    }

    *//**
     * 微信注册
     *//*
    @PostMapping("/wxRegister")
    @ApiOperation("微信注册")
    @ApiImplicitParam(name = "user", value = "用户信息", required = true)
    public AjaxResult wxRegister(@RequestBody EasyfitUsers user) {
        // 检查用户是否已存在
        if (userService.selectEasyfitUsersByOpenid(user.getOpenid()) != null) {
            return AjaxResult.error("用户已存在");
        }

        // 设置默认值
        user.setStatus("0"); // 正常状态

        // 保存用户
        int rows = userService.insertEasyfitUsers(user);
        if (rows > 0) {
            // 生成token - 直接调用静态方法
            String token = TokenUtils.generateToken(user);

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", user);

            return AjaxResult.success("注册成功", result);
        }
        return AjaxResult.error("注册失败");
    }*/
}
